﻿Imports VB = Microsoft.VisualBasic
Public Class frmMain
    Private MyActiveLock As ActiveLock3_6NET._IActiveLock
    Private WithEvents ActiveLockEventSink As ActiveLock3_6NET.ActiveLockEventNotifier
    Const LICENSE_ROOT As String = "TestApp"
    ' Trial information string
    Public strMsg, strRemainingTrialDays, strRemainingTrialRuns, strTrialLength As String
    Public strUsedDays, strExpirationDate, strRegisteredUser, strRegisteredLevel As String
    Public strLicenseClass, strMaxCount, strLicenseFileType, strLicenseType, strUsedLockType As String
    Public remainingDays, remainingRuns As Integer
    Public totalDays, totalRuns As Integer
    ' Trial mode variables
    Dim noTrialThisTime As Boolean 'ialkan - needed for registration while form was loaded via trial
    Dim expireTrialLicense As Boolean
    Dim strKeyStorePath As String
    Dim strAutoRegisterKeyPath As String

    Public Const PUB_KEY As String = "RSA1024<RSAKeyValue><Modulus>sVldAatSH3QNjf2cWCWV6uDwXLqIohy0Clsw3H1MOJDqPZurAqkEMPZS4WySgx5Ycpqu7dYeYJj0Hwz+rs6z9kXIMelLzqWSdJOwmRjlOdXVwWSTl+UxdhSxudVUQgNH1mjxPy0D/1QUXmiwAO6Fw1uRamkxvtk3pZjcvIE7GGE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim boolAutoRegisterKeyPath As Boolean
        Dim Msg As String

        ' Set the path to the license file (LIC) and ALL file (if it exists)
        Dim Ret As Long
        Dim AppfilePath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)


        'The second line is used when unmanaged Activelock3NET.dll is used
        Dim MyAL As New ActiveLock3_6NET.Globals
        'Dim MyAL As New ActiveLock3.Globals

        ' Set a new instance of the Activelock object
        MyActiveLock = MyAL.NewInstance()

        With MyActiveLock

            ' Set the software/application name
            .SoftwareName = LICENSE_ROOT
            txtName.Text = .SoftwareName

            ' Set the software/application version number
            ' Note: Do not use (App.Major & "." & App.Minor & "." & App.Revision)
            ' since the license will fail with version incremented via exe rebuilds
            ' THE FOLLOWING IS A SAMPLE USAGE
            ' WARNING *** WARNING *** DO NOT USE App.Major & "." & App.Minor & "." & App.Revision
            '.SoftwareVersion = "1.3.2"   
            .SoftwareVersion = "3.6" ' WARNING *** WARNING *** DO NOT USE App.Major & "." & App.Minor & "." & App.Revision
            txtVersion.Text = .SoftwareVersion

            ' Set the software/application password
            ' This should be set to protect yourself against ResetTrial abuse
            ' The password is also used by the short keys
            ' Regular licensing does not use this password, but you should still use a password
            ' WARNING: You can not ignore this property. You *must* set a password.
            .SoftwarePassword = "fgh789"

            ' Set whether the software/application will use a short key or RSA method
            ' alsRSA covers RSA native classes approach.
            ' RSA classes in .NET allows you to pick from several cipher strengths
            ' alsShortKeyMD5 is for short key protection only
            ' WARNING: Short key licenses use the lockFingerprint by default
            '.LicenseKeyType = ActiveLock3_6NET.IActiveLock.ALLicenseKeyTypes.alsShortKeyMD5
            .LicenseKeyType = ActiveLock3_6NET.IActiveLock.ALLicenseKeyTypes.alsRSA

            ' Set the Trial Feature properties
            ' If you don't want to use the trial feature in your app, set the TrialType
            ' property to trialNone.

            ' Set the trial type property
            ' this is either trialDays, or trialRuns or trialNone.
            '.TrialType = ActiveLock3_6NET.IActiveLock.ALTrialTypes.trialRuns
            .TrialType = ActiveLock3_6NET.IActiveLock.ALTrialTypes.trialDays

            ' Set the Trial Length property.
            ' This number represents the number of days or the number of runs (whichever is applicable).
            .TrialLength = 30
            If .TrialType <> ActiveLock3_6NET.IActiveLock.ALTrialTypes.trialNone And .TrialLength = 0 Then
                ' In such cases Activelock automatically generates errors -11001100 or -11001101
                ' to indicate that you're using the trial feature but, trial length was not specified
            End If

            ' Comment the following statement to use a certain trial data hiding technique
            ' Use OR to combine one or more trial hiding techniques
            ' or don't use this property to use ALL techniques
            ' WARNING: trialRegistryPerUser is "Per User"; this means each user trial feature 
            ' is controlled that user's own registry hive.
            ' This means initiating a trial with one user does not initiate a trial for another user.
            ' trialHiddenFolder and trialSteganography are for "All Users"
            '.TrialHideType = ActiveLock3_6NET.IActiveLock.ALTrialHideTypes.trialHiddenFolder Or ActiveLock3_6NET.IActiveLock.ALTrialHideTypes.trialRegistryPerUser Or ActiveLock3_6NET.IActiveLock.ALTrialHideTypes.trialSteganography
            .TrialHideType = ActiveLock3_6NET.IActiveLock.ALTrialHideTypes.trialSteganography

            ' Use the following if you'd like to make the trial warning message persistent 
            ' until a license is registered.
            ' Expiration of the trial is not so clear to some users without any warnings.
            ' .trialWarningTemporary will show the trial expired warning only once.
            .TrialWarning = ActiveLock3_6NET.IActiveLock.ALTrialWarningTypes.trialWarningPersistent

            ' Set the Software code
            ' This is the same thing as VCode
            ' Run Alugen first and create a VCode and GCode 
            ' for the software name and version number you used above
            ' Then copy and use the VCode as the PUB_KEY here.
            ' It's up to you to encrypt it; just makes it more secure
            ' Enc encodes, Dec decodes the public key (VCode)
            ' Change Enc() and Dec(0 the way you want.
            '.SoftwareCode = Dec(PUB_KEY)
            .SoftwareCode = PUB_KEY

            ' uncomment the following when unmanaged Activelock3NET.dll is used
            '.LockType = ActiveLock3.ALLockTypes.lockNone

            ' Set the Hardware keys
            ' In order to pick the keys that you want to lock to in Alugen, use lockNone only
            ' Example: lockWindows Or lockComp
            ' You can combine any lockType(s) using OR as above
            ' WARNING: Short key licenses use the lockFingerprint by default
            ' WARNING: This has no effect for short key licenses
            .LockType = ActiveLock3_6NET.IActiveLock.ALLockTypes.lockNone
            '.LockType = ActiveLock3_6NET.IActiveLock.ALLockTypes.lockFingerprint
            '.LockType = ActiveLock3_6NET.IActiveLock.ALLockTypes.lockIP Or _
            'ActiveLock3_6NET.IActiveLock.ALLockTypes.lockComp

            ' If you want to lock to any keys explicitly, combine them using OR
            ' But you won't be able to uncheck/check any of them while in Alugen (too late at that point).
            '.LockType = _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockBIOS Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockComp Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockHD Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockHDFirmware Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockIP Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockMotherboard Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockWindows Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockMAC Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockExternalIP Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockFingerprint Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockSID Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockCPUID Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockBaseboardID Or _
            ' ActiveLock3_6NET.IActiveLock.ALLockTypes.lockVideoID

            ' USAGE OF .ALL (AUTO-REGISTER) FILES
            ' THESE FILES CARRY THE LICENSE (LIBERATION) KEY FOR AUTO REGISTRATION
            ' ALL FILES ARE NOT USED WITH SHORT-KEY LICENSES
            ' Set the .ALL file path if you're using an ALL file.
            ' .ALL is an auto registration file.
            ' You generate .ALL files via Alugen and then send to the users
            ' They put the .ALL file in the directory you specify below
            ' .ALL simply contains the license key
            ' WARNING: .ALL files are deleted after they are used.
            ' It is recommended that you use both SoftwareName and Version in the .ALL filename
            ' since multiple .ALL files might exist in the same directory
            ' If you don't want to use the software name and version number explicitly, use an .ALL
            ' filename that is specific to this application
            ' Be aware that Alugen will not accept creation of ALL files without
            ' the software name and version in the ALL filename.
            ' You can rename the ALL file afterwards, but that name should match the ALL filename used here.

            ' .ALL FILE STORAGE OPTION-1
            ' Try to use the simplest accessible solution for both XP and Vista such as C:\TEMP
            If My.Computer.FileSystem.DirectoryExists("c:\temp") = False Then
                My.Computer.FileSystem.CreateDirectory("c:\temp")
            End If
            strAutoRegisterKeyPath = "c:\temp\" & .SoftwareName & .SoftwareVersion & ".all"

            ' .ALL FILE STORAGE OPTION-2
            ' The following (AppfilePath) is another option for both XP and Vista
            ' but you should be sure that the directory exists.
            ' Since this is also the folder where the LIC file resides, it's not recommended
            'If Directory.Exists(AppfilePath & "\" & .SoftwareName & .SoftwareVersion) = False Then
            '    MkDir(AppfilePath & "\" & .SoftwareName & .SoftwareVersion)
            'End If
            'strAutoRegisterKeyPath = AppfilePath & "\" & .SoftwareName & .SoftwareVersion & "\" & .SoftwareName & .SoftwareVersion & ".all"

            ' .ALL FILE STORAGE OPTION-3
            ' AppPath could be an option for XP, but not for Vista
            'If Directory.Exists(AppPath & "\" & .SoftwareName & .SoftwareVersion ) = False Then
            '    MkDir(AppPath & "\" & .SoftwareName & .SoftwareVersion)
            'End If
            'strAutoRegisterKeyPath = AppPath() & "\" & .SoftwareName & .SoftwareVersion & "\" & .SoftwareName & .SoftwareVersion & ".all"

            .AutoRegisterKeyPath = strAutoRegisterKeyPath

            If My.Computer.FileSystem.FileExists(strAutoRegisterKeyPath) Then boolAutoRegisterKeyPath = True

            ' Set if auto registration will be used.
            ' Auto registration uses the ALL file for license registration.
            .AutoRegister = ActiveLock3_6NET.IActiveLock.ALAutoRegisterTypes.alsEnableAutoRegistration

            ' Set the Time Server check for Clock Tampering
            ' This is optional but highly recommended.
            ' Although Activelock makes every effort to check if the system clock was tampered,
            ' checking a time server is the guaranteed way of knowing the correct UTC time/day.
            ' This feature might add some delay to your apps start-up time.
            .CheckTimeServerForClockTampering = ActiveLock3_6NET.IActiveLock.ALTimeServerTypes.alsDontCheckTimeServer       ' use alsCheckTimeServer to enforce time server checks for clock tampering check
            '.CheckTimeServerForClockTampering = ActiveLock3_6NET.IActiveLock.ALTimeServerTypes.alsCheckTimeServer

            ' Set the system files clock tampering check
            ' This feature might add some delay to your apps start-up time.
            .CheckSystemFilesForClockTampering = ActiveLock3_6NET.IActiveLock.ALSystemFilesTypes.alsDontCheckSystemFiles    ' use alsCheckSystemFiles to enforce system files scanning for clock tampering check
            '.CheckSystemFilesForClockTampering = ActiveLock3_6NET.IActiveLock.ALSystemFilesTypes.alsCheckSystemFiles

            ' Set the license file format; this could be encrypted or plain
            ' Even in a plain file format, certain keys and dates are still encrypted.
            .LicenseFileType = ActiveLock3_6NET.IActiveLock.ALLicenseFileTypes.alsLicenseFilePlain

            ' Initialize the keystore. We use a File keystore in this case.
            ' The other type alsRegistry is NOT supported.
            .KeyStoreType = ActiveLock3_6NET.IActiveLock.LicStoreType.alsFile
            ' uncomment the following when unmanaged Activelock3NET.dll is used
            'MyActiveLock.KeyStoreType = ActiveLock3.LicStoreType.alsFile

            ' The code below will put the LIC file inside the "...\All Users\Documents" folder
            ' You can hard code this path and put the LIC file anywhere you want
            ' But be careful with limited user accounts in Vista.
            ' It's recommended that you put this file in shared and accessible folders in Vista
            ' It is recommended that you use both SoftwareName and Version in the LIC filename
            ' since multiple LIC files might exist in the same directory
            ' If you don't want to use the software name and version number explicitly, use an LIC
            ' filename that is specific to this application
            If My.Computer.FileSystem.DirectoryExists("C:\temp") = False Then
                MkDir("C:\temp")
            End If
            strKeyStorePath = "C:\temp\" & .SoftwareName & .SoftwareVersion & ".lic"
            ' AppPath could be an option for XP, but not so for Vista
            'If Directory.Exists(AppPath & "\" & .SoftwareName & .SoftwareVersion ) = False Then
            '    MkDir(AppPath & "\" & .SoftwareName & .SoftwareVersion)
            'End If
            'strKeyStorePath = AppPath() & "\" & .SoftwareName & .SoftwareVersion & "\" & .SoftwareName & .SoftwareVersion & ".lic"
            .KeyStorePath = strKeyStorePath

            ' Obtain the EventNotifier so that we can receive notifications from AL.
            ' Do Not Change This  - unless you know what this is for.
            ActiveLockEventSink = .EventNotifier

            ' Initialize Activelock 
            ' Use the following with ASP.NET applications
            ' MyActiveLock.Init(Application.StartupPath & "\bin")
            ' Use the following with VB.NET applications
            .Init(Application.StartupPath, strAutoRegisterKeyPath)
            If My.Computer.FileSystem.FileExists(strKeyStorePath) And boolAutoRegisterKeyPath = True And strAutoRegisterKeyPath <> "" Then
                ' This means, an ALL file existed and was used to create a LIC file
                ' Init() method successfully registered the ALL file
                ' and returned the license key
                ' You can process that key here to see if there is any abuse, etc.
                ' ie. whether the key was used before, etc.
            End If

        End With


        ' Check registration status
        ' Acquire() method does both trial and regular licensing
        ' If it generates an error, that means there NO trial, NO license
        ' If no error and returns a string, there's a trial but No license. Parse the string to display a trial message.
        ' If no error and no string returned, you've got a valid license.

        ' In case the Acquire method generates an error, so no license and no trial:
        ' If InStr(1, Err.Description, "No valid license") > 0 Or InStr(1, Err.Description, "license invalid") > 0 Then '-2147221503 & -2147221502
        Try
            MyActiveLock.Acquire(strMsg, strRemainingTrialDays, strRemainingTrialRuns, strTrialLength, strUsedDays, strExpirationDate, strRegisteredUser, strRegisteredLevel, strLicenseClass, strMaxCount, strLicenseFileType)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            GoTo Err
        End Try
        ' strMsg is to get the trial status
        ' All other parameters are Optional and you can actually get all of them
        ' using MyActivelock.Property usage, but keep in mind that 
        ' doing so will check the license every time making this a time consuming 
        ' way of reading those properties
        ' The fastest approach is to use the arguments from Acquire() method.
        If strMsg <> "" Then 'There's a trial
            ' Parse the returned string to display it on a form
            Dim A() As String = strMsg.Split(vbCrLf)
            txtRegStatus.Text = A(0).Trim
            txtUsedDays.Text = A(1).Trim

            ' You can also get the RemainingTrialDays or RemainingTrialRuns directly by:
            'txtRemainingTrialDays.Text = MyActiveLock.RemainingTrialDays OR MyActiveLock.RemainingTrialRuns
            ' At this point RemainingTrialDays and RemainingTrialRuns properties are directly accessible
            ' Even if you don't want to show a trial form at this point, you still know the 
            ' trial status with one of these two properties (whichever is applicable).
            'FunctionalitiesEnabled = True


            ' ALTERNATIVE 2
            ' Show a splash form that shows two choices, register or try
            ' User must chosse one option for the form to close
            'MyActiveLock.RemainingTrialDays
            remainingDays = CInt(strRemainingTrialDays)
            remainingRuns = CInt(strRemainingTrialRuns)
            'MyActiveLock.TrialLength
            totalDays = CInt(strTrialLength)
            totalRuns = CInt(strTrialLength)
            Me.Refresh()
            Exit Sub
        Else
            MessageBox.Show("This is a fullversion software")
            EnableControls(strRegisteredLevel)
        End If

        ' You can retrieve the LockTypes set inside Alugen
        ' by accessing the UsedLockType property
        'For example, if only lockHDfirmware was used, this will return 256
        'MsgBox(MyActiveLock.UsedLockType)

        ' So far so good... 
        ' If you are here already, that means you have a valid license.
        ' Set the textboxes in your app accordingly.
        txtRegStatus.Text = "Registered"
        'MyActiveLock.UsedDays
        txtUsedDays.Text = strUsedDays
        'MyActiveLock.ExpirationDate

        ' This will display the date in user's locale short date format
        Dim strSD As String = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
        Dim strST As String = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern

        txtExpiration.Text = Convert.ToDateTime(strExpirationDate).ToString(strSD & " " & strST)
        If txtExpiration.Text = "" Then
            txtExpiration.Text = "Permanent" 'App has a permanent license
        End If

        Dim arrProdVer() As String
        'MyActiveLock.RegisteredUser
        arrProdVer = Split(strRegisteredUser, "&&&") ' Extract the software name and version
        txtUser.Text = arrProdVer(0)

        'MyActiveLock.RegisteredLevel
        txtRegisteredLevel.Text = strRegisteredLevel

        ' Set Networked Licenses if applicable
        'MyActiveLock.LicenseClass
        'If strLicenseClass = "MultiUser" Then
        'txtNetworkedLicense.Text = "Networked"
        'Else
        'txtNetworkedLicense.Text = "Single User"
        'txtMaxCount.Visible = False
        'lblConcurrentUsers.Visible = False
        'End If
        ' This is for number of concurrent users count in a netwrok license
        'MyActiveLock.MaxCount
        'txtMaxCount.Text = strMaxCount

        ' Read the license file into a string to determine the license type
        ' You can read the LicenseType from the LIC file directly
        ' However, the LIC file should be in Plain format for this to work.
        ' MyActiveLock.LicenseFileType
        If strLicenseFileType = ActiveLock3_6NET.IActiveLock.ALLicenseFileTypes.alsLicenseFilePlain Then
            Dim strBuff As String
            Dim fNum As Short
            fNum = FreeFile()
            FileOpen(fNum, strKeyStorePath, OpenMode.Input)
            strBuff = InputString(1, LOF(1))
            FileClose(fNum)
            If Instring(strBuff, "LicenseType=3") Then
                txtLicenseType.Text = "Time Limited"
            ElseIf Instring(strBuff, "LicenseType=1") Then
                txtLicenseType.Text = "Periodic"
            ElseIf Instring(strBuff, "LicenseType=2") Then
                txtLicenseType.Text = "Permanent"
            End If
        Else
            If strLicenseType = "3" Then
                txtLicenseType.Text = "Time Limited"
            ElseIf strLicenseType = "1" Then
                txtLicenseType.Text = "Periodic"
            ElseIf strLicenseType = "2" Then
                txtLicenseType.Text = "Permanent"
            End If
        End If
        Exit Sub
Err:
        MyActiveLock.ResetTrial()
        MyActiveLock.ResetTrial()
    End Sub


    Function Instring(ByVal x As String, ByVal ParamArray MyArray() As Object) As Boolean
        'Do ANY of a group of sub-strings appear in within the first string?
        'Case doesn't count and we don't care WHERE or WHICH
        Dim y As Object 'member of array that holds all arguments except the first
        For Each y In MyArray
            If InStr(1, x, y, 1) > 0 Then 'the "ones" make the comparison case-insensitive
                Instring = True
                Exit Function
            End If
        Next y
    End Function



    Private Sub EnableControls(ByVal Level As Integer)
        Select Case Level
            Case 0
                cmdLevel0.Enabled = True
            Case 5
                cmdLevel5.Enabled = True
            Case Else
                MessageBox.Show("What level is this ?")
        End Select

    End Sub


    Private Sub txtUser_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtUser.KeyUp
        If e.KeyCode = Keys.Enter Then
            Me.Cursor = Cursors.WaitCursor
            txtInstallCode.Text = MyActiveLock.InstallationCode(txtUser.Text)
            Me.Cursor = Cursors.Default
        End If
    End Sub

    Private Sub cmdRegister_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegister.Click
        Try
            MyActiveLock.Register((InputBox("Enter the activation code")))
            MessageBox.Show("Restart application.")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        
    End Sub

    Private Sub txtUser_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtUser.TextChanged

    End Sub
End Class